import { IFileUtils } from '../interface/IFileUtils';

class FileUtils implements IFileUtils {
  constructor() {}

  public fileDownload(data: Blob, type: string, filename: string): boolean {
    let flag = true;
    try {
      let blob = new Blob([data], { type: type });
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement('a'); // 创建a标签
      link.href = url;
      link.download = filename;
      link.click();
      URL.revokeObjectURL(url); // 释放内存
      flag = true;
    } catch (e) {
      flag = false;
      console.error('error: ', e);
    }

    return flag;
  }

  getHeadersFileInfo(val: any): { fileName: string; type: string } {
    const fileName =
      decodeURIComponent(val.headers['content-disposition']).split(
        'filename='
      )[1] ?? val.name;
    const type =
      val.headers['content-type'].split('/')[1] ?? 'application/octet-stream';
    return { fileName, type };
  }

  fileSelector(options?: {
    accept?: string;
    multiple?: boolean;
  }): Promise<FileList | File | null> {
    return new Promise((resolve) => {
      // 创建隐藏的文件输入元素
      const fileInput: any = document.createElement('input');
      fileInput.type = 'file';
      fileInput.style.display = 'none';

      // 应用配置选项
      if (options && options.accept) fileInput.accept = options.accept;
      if (options && options.multiple) fileInput.multiple = true;

      // 添加到文档中
      document.body.appendChild(fileInput);

      // 处理文件选择
      fileInput.addEventListener('change', () => {
        const files = fileInput.files;
        resolve(options && options.multiple ? files : files[0] || null);
        cleanup();
      });

      // 处理取消选择（当对话框关闭但未选择文件时）
      fileInput.addEventListener('blur', () => {
        setTimeout(() => {
          if (!fileInput.files.length) {
            resolve(null);
            cleanup();
          }
        }, 300);
      });

      // 清理函数
      const cleanup = () => {
        document.body.removeChild(fileInput);
      };

      // 触发文件选择对话框
      fileInput.click();
    });
  }
}

const fileUtils = new FileUtils();
export default fileUtils;
